package com.gang.adminsecurity.commom.exception;

import com.gang.adminsecurity.commom.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.nio.file.AccessDeniedException;

/**
 * 全局异常处理
 *
 * @author huohuo
 * @createDate 2021-09-10
 * @email gang95@email.cn
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = AccessDeniedException.class)
    public R<String> handler(AccessDeniedException e) {
        log.info("security权限不足：----------------{}", e.getMessage());
        return R.failed("security权限不足");
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R<String> handler(MethodArgumentNotValidException e) {
        log.info("实体校验异常：----------------{}", e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
        return R.failed(objectError.getDefaultMessage());
    }

    @ExceptionHandler(value = IllegalArgumentException.class)
    public R<String> handler(IllegalArgumentException e) {
        log.error("Assert异常：----------------{}", e.getMessage());
        return R.failed(e.getMessage());
    }

    @ExceptionHandler(value = RuntimeException.class)
    public R<String> handler(RuntimeException e) {
        log.error("运行时异常：----------------{}", e.getMessage());
        return R.failed(e.getMessage());
    }
}
